package com.netty.handler;

import com.netty.CIMUdpRequestHandler;
import com.netty.constant.Constants;
import com.netty.utils.Md5Utils;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * @author zl
 * @version 1.0
 * @date 2021/9/29 16:19
 */
public class ImUdpServerHandler extends SimpleChannelInboundHandler<DatagramPacket> {
    private Logger logger = LoggerFactory.getLogger(getClass());

    private CIMUdpRequestHandler cimRequestHandler;

    public ImUdpServerHandler(CIMUdpRequestHandler cimRequestHandler) {
        this.cimRequestHandler = cimRequestHandler;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.channel().attr(Constants.SessionConfig.ID).set(Md5Utils.shortMd5(ctx.channel().id().asLongText()));
        ctx.channel().attr(Constants.SessionConfig.CHANNEL).set(Constants.ImserverConfig.UDPSOCKET);
        cimRequestHandler.channelActive(ctx.channel());
    }

    //消息没有结束的时候触发
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, DatagramPacket datagramPacket) throws Exception {
        Constants.executorService.submit(new Runnable() {
            @Override
            public void run() {
                cimRequestHandler.channelRead0(channelHandlerContext.channel(), datagramPacket);
            }
        });
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.info(">>>>>>>>>>>>>>>>>>>>>>channel 捕获到异常了，关闭了{}<<<<<<<<<<<<<<<<<<<<<<", cause);
        super.exceptionCaught(ctx, cause);
    }

}
